Python alapok


a = 42
b = 'asd' # string
c = "asd" # also a string
d = f"{a} is a number" # format string
d = "%d is a number" % a # format string
e, f = 5, 6
f, e = e, f # swap values

3 ** 2

3 // 2

import math

math.ceil(3.8)
math.floor(3.8)
round(3.8)
round(3.8, 1)

a = 10
b = 5

print(f"a & b: {a & b}") # AND
print(f"a | b: {a | b}") # OR
print(f"a ^ b: {a ^ b}") # XOR
print(f"a << 1: {a << 1}") # Left Shift
print(f"a >> 1: {a >> 1}") # Right Shift
print(f"~a: {~a}") # NOT

b = "   I'm a String   " # string

b.upper()
b.lower()
b.strip() # remove whitespaces
b.lstrip() # remove whitespaces from the left
b.rstrip() # remove whitespaces from the right
b.replace("a", "b")
b.split("s")

l = [1, 2, 'a', [5, 6]]
l[3] # indexing
l[-1] # last element
l.append("b")
l.insert(2, "b") # index, item
l.extend([1, 2, 3])

3 in l # is 3 in the list?

l.remove("b") # remove a specific item
del l[2] # remove item on a specific index

l.clear() # remove all items from the list but the list is still available
del l # delete the whole list

l = [1, 2, 'a', [5, 6]]

l[1:] # slice from index 1 to the end
l[:-1] # slice from the beginning to the second last element
l[1:-1] # slice from index 1 to the second last element
l[1:-1:2] # slice with step 2

l[1:2] == l[1] # False, [2] != 2

l = (1, 'a', "c", 3)
del l[2] # Error
l[2] = 'a' # Error

Szótár (dictionary):


team = { 91: "Ayers, Robert", 13: "Beckham Jr,", 3: "Brown, Josh", 54: "Casillas, Jonathan", 21: "Collins, Landon" }

len(team) # length of the dictionary
team[3]
team[2] = "Brown" # add new elem
del team[2] # remove elem

team.keys()
team.values()
team.items()

Lista, tuple, szótár generálás:


mylist = [ x * x for x in range(10) ] # [0,1,4,9,16,25,36,64,81]
mydict = { x: x * x for x in range(5) } # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
mydict2 = { x: x * x for x in range(5) if x != 2 } # {0: 0, 1: 1, 3: 9, 4: 16}
mytuple = tuple( x * x for x in range(3) )

Elágazások, ciklusok:


if 100 in team:
    print('Yes, 100 is in the team')
elif 76 in team:
    print('100 is not in the team, but 76 is in it...')
else:
    print('Both 100 and 76 are not in the team')

for num, name in team.items():
    print(num, name, end="\t", sep=": ")
print("")

for i in range(2, 10, 2):
    print(i)
else:
    print(i)

i = 1
while i < 10:
    print(i)
    i += 1
else:
    print(i)

Függvények:


def is_even(num: int = 5):
    if num % 2 == 0:
        return True
    else:
        return False

def is_even2(num: int = 5):
    if num % 2 == 0:
        return True, num
    else:
        return False, num

print(is_even2())

Globális változók:


x = "awesome"

def myfunc():
    x = "fantastic" # override the global variable in this scope
    print("Python is " + x)

myfunc()
print("Python is " + x) # this is the original 'x'

x = "awesome"

def myfunc():
  global x
  x = "fantastic"
  print("Python is " + x)
  
myfunc()
print("Python is " + x)

Lambda függvények:


is_even = lambda num: (num % 2) == 0
print(is_even(2))

Map, filter:


def celsius(T):
    return (float(5) / 9) * (T - 32)

temperatures = (97.7, 98.60000000000001, 99.5, 100.4, 102.2)
temperatures_in_C = list(map(celsius, temperatures))
print(temperatures_in_C) # [36.5, 37.00000000000001, 37.5, 38.00000000000001, 39.0]

fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
odd_nums = list(filter(lambda x: x % 2, fibonacci))
print(odd_nums) # [1, 1, 3, 5, 13, 21, 55]

Main:


if __name__ == "__main__":
    print("run")

Standard input és try-except:


x = input("Give me a number: ") # always string

try:
    x = int(x)
    print(x)
except:
    print("This is not a number")

Parancssori argumentumok és import:


import sys

print(sys.argv[0]) # the name of the script
print(sys.argv[1])

from sys import argv

print(argv[0]) # the name of the script
print(argv[1])

Osztályok:


class Student:
    students = 0

    def __init__(self, _name: str, _point: int) -> None:
        self.name = _name
        self.point = _point
        self.__increment_students()

    def __str__(self) -> str:
        return self.name + "(" + str(self.point) + ")"

    @staticmethod
    def get_students() -> int: # static method
        return Student.students

    def __increment_students(self) -> None: # private method
        Student.students += 1


p = Student("Ford", 20)
print(p)
print(p.students)
print(p.get_students())
print(p.__increment_students()) # error

JSON:


import json

json_string = """
{
    "researcher": {
        "name": "Ford Prefect",
        "species": "Betelgeusian",
        "relatives": [
            {
            "name": "Zaphod Beeblebrox",
            "species": "Betelgeusian"
            }
        ]
    }
}
"""
 

data = json.loads(json_string)
for rel in data["researcher"]["relatives"]:
    print('Name: %s (%s)' % (rel["name"], rel["species"]))
Fájlból beolvasva figyelni kell arra, hogy nem a loads függvényt kell használni, hanem a load függvényt.

import json

with open("data_file.json", "r") as read_file:
    data = json.load(read_file)
    print(data["president"]["name"])

Fájl műveletek:


f = open("demo.txt", "r") # w - write, a - append
for line in f:
    print(line, end="")
f.close()

with open("demo.txt", "r") as f:
    for line in f:
        print(line, end="")

with open("input.txt", "rb") as f:
    print(f.read(9)) # b'some text'

with open('input.txt', 'r') as f:
    row = f.readline()
    print('current row', row) # current row 1. row
    row = f.readline()
    print('current row', row) # current row 2. row

    f.seek(0, 0) # f.seek(offset, whence)
    row = f.readline()
    print('current row', row) # current row 1. row

Bájtsorrend:

Struktúra:


import struct

values = (1, "ab".encode(), 2.7)
packer = struct.Struct("i 2s f") # int, char[2], float
packed_data = packer.pack(*values)
print(packed_data) # b'\x01\x00\x00\x00ab\x00\x00\xcd\xcc,@'

unpacker = struct.Struct("i 2s f")
unpacked_data = unpacker.unpack(packed_data)
print(unpacked_data)

import struct

packer = struct.Struct("i 2s f")
print(struct.calcsize("i 2s f "))
print(packer.size)

import struct

str = "hello"
packed_str = struct.pack('8s', str.encode())

d = struct.unpack('8s', packed_str)
print(d[0].decode().strip('\x00'))

import struct

packer = struct.Struct('i3si')
with open('dates.bin', 'wb') as f:
    for i in range(5):
        values = (2020 + i, b'jan', 10 + i)
        packed_data = packer.pack(*values)
        f.write(packed_data)

import struct

packer = struct.Struct('i3si')
with open('dates.bin', 'rb') as f:
    f.seek(packer.size * 4)
    data = f.read(packer.size)
    print(packer.unpack(data)) ### output: (2024, b'jan', 14)

Kiegészítő anyag:


import time
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-t', '--time', type=float, help='set wait time')
args = parser.parse_args()

if args.time != None:
    time.sleep(float(args.time))
    print(f"We waited: {args.time} seconds")

python test.py -t 3

Feladatok